// src/stores/auth.ts
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { jwtDecode } from 'jwt-decode'

interface JwtPayload {
  sub: number
  username: string
  role: number
  storeName?: string
  [key: string]: any
}

export const useAuthStore = defineStore(
  'auth',
  () => {
    const token = ref('')

    const payload = computed<JwtPayload>(() =>
      token.value ? jwtDecode<JwtPayload>(token.value) : ({} as JwtPayload)
    )

    // ✅ 新增计算属性 userId
    const userId = computed(() => payload.value?.sub || 0)

    const setToken = (t: string) => (token.value = t)
    const clear = () => (token.value = '')

    // ✅ 记得 return userId
    return { token, payload, userId, setToken, clear }
  },
  { persist: true } as any
)